<script setup lang="ts">
import { CirclePlus, DocumentAdd, Edit, Search, ArrowRight, Briefcase, OfficeBuilding } from "@element-plus/icons-vue";
import ResumePreview from "@/views/createTemplate/previewer/index.vue";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import appStore from "@/store";
import { getResumeJsonById, getResumeList } from "@/http/m_api/template";
import { formatDate } from "@/assets/ts/utils";
import { getRequirement } from "@/http/m_api/interview";

const { interviewNewStore } = storeToRefs(appStore.useInterviewJsonStore);

interface History {
  value: string;
}

const legoCreateList = ref<Array<any>>([]);
const loadingList = ref(false);
const selecting = ref(-1);
const company = ref('');
const post = ref('');
const company_history = ref<History[]>([]);
const post_history = ref<History[]>([]);
const post_requirement = ref('');
const { HJNewJsonStore, resumeId } = storeToRefs(appStore.useCreateTemplateStore);

// Animation states
const fadeIn = ref(false);
const resumeSelected = ref(false);

onMounted(() => {
  getUserTemplateList();

  let itemCompany = localStorage.getItem("CompanyHistory");
  if (itemCompany) company_history.value = JSON.parse(itemCompany);
  let itemPost = localStorage.getItem("PostHistory");
  if (itemPost) post_history.value = JSON.parse(itemPost);
  company.value = interviewNewStore.value.Settings.company;
  post.value = interviewNewStore.value.Settings.post;
  post_requirement.value = interviewNewStore.value.Settings.requirement;

  // Trigger animations after mount
  setTimeout(() => {
    fadeIn.value = true;
  }, 100);
});

const getUserTemplateList = async () => {
  let page = 1, limit = 100;
  loadingList.value = true;
  const data = await getResumeList(page, limit);
  if (data.code === 0) {
    loadingList.value = false;
    legoCreateList.value = data.data.list;
    legoCreateList.value.map((item: any) => {
      item.previewUrl = item.templateCover;
    });
    if (interviewNewStore.value.Settings.resumeId !== -1) {
      await getUserTemplate(interviewNewStore.value.Settings.resumeId.toString());
      legoCreateList.value.forEach((item) => {
        if (item.id === interviewNewStore.value.Settings.resumeId) {
          selecting.value = item.id;
          resumeSelected.value = true;
        }
      });
    }
  } else {
    ElMessage.error(data.message);
  }
};

const searching = ref(false);

const search = async () => {
  if (company.value != '') {
    const index = company_history.value.findIndex(item => item.value === company.value);

    if (index !== -1) {
      company_history.value.splice(index, 1);
    }
    company_history.value.unshift({value: company.value});
    localStorage.setItem("CompanyHistory", JSON.stringify(company_history.value));
  }
  if (post.value != '') {
    const index = post_history.value.findIndex(item => item.value === post.value);
    if (index !== -1) {
      post_history.value.splice(index, 1);
    }
    post_history.value.unshift({value: post.value});
    localStorage.setItem("PostHistory", JSON.stringify(post_history.value));
  }
  if (company.value !== '' && post.value !== '') {
    searching.value = true;
    const data = await getRequirement(company.value, post.value);
    if(data.code === 0){
      post_requirement.value = '岗位描述：\n';
      post_requirement.value += `${data.data.jobDescription}\n\n`;
      post_requirement.value += `基本要求\n`;
      post_requirement.value += `${data.data.basicRequirements}\n\n`;
      post_requirement.value += `技能要求\n`;
      post_requirement.value += `${data.data.skillRequirements}\n\n`;
      post_requirement.value += `加分项\n`;
      post_requirement.value += `${data.data.bonusPoints}\n\n`;
    } else {
      ElMessage.error('出现错误，当前无法自动填充！');
    }
    searching.value = false;
  } else {
    ElMessage.warning("请先将公司和岗位填写完毕！");
  }
};

const handleCommand = (command: number) => {
  selecting.value = command;
  if (command >= 0) {
    getUserTemplate(legoCreateList.value[command].id);
    resumeSelected.value = true;
  }
};

const loadingPreview = ref(false);

const getUserTemplate = async (id: string) => {
  loadingPreview.value = true;
  const data = await getResumeJsonById(id);
  if (data.code === 0) {
    HJNewJsonStore.value = JSON.parse(data.data.templateJson);
    HJNewJsonStore.value.props.title = HJNewJsonStore.value.config.title;
    interviewNewStore.value.Settings.resumeId = Number.parseInt(id);
    resumeId.value = Number.parseInt(id);
    loadingPreview.value = false;
  }
};

const router = useRouter();

const finish = () => {
  interviewNewStore.value.Settings.company = company.value;
  interviewNewStore.value.Settings.post = post.value;
  interviewNewStore.value.Settings.requirement = post_requirement.value;
  router.push('/interview/setting');
};

// Progress calculation
const progressPercentage = computed(() => {
  let progress = 0;
  if (selecting.value !== -1) progress += 40;
  if (company.value) progress += 20;
  if (post.value) progress += 20;
  if (post_requirement.value) progress += 20;
  return progress;
});
</script>

<template>
  <div class="interview-setting-container" :class="{ 'fade-in': fadeIn }">
    <!-- Header with progress indicator -->
    <div class="page-header">
      <h1 class="page-title">面试准备 <span class="highlight">选择需求</span></h1>
      <div class="progress-container">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${progressPercentage}%` }"></div>
        </div>
        <div class="progress-text">{{ progressPercentage }}% 完成</div>
      </div>
    </div>

    <div class="content-container">
      <!-- Left column: Resume selection and preview -->
      <div class="resume-section">
        <div class="section-header">
          <el-dropdown trigger="click" @command="handleCommand" placement="bottom-start">
            <div class="resume-selector" :class="{ 'has-selection': selecting !== -1 }">
              <el-icon class="selector-icon">
                <CirclePlus v-if="selecting === -1" />
                <DocumentAdd v-else />
              </el-icon>
              <span class="selector-text">{{ selecting === -1 ? '请选择本次投递的简历' : '已选择简历' }}</span>
              <el-icon class="dropdown-arrow"><ArrowRight /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu v-if="!loadingList" class="custom-dropdown">
                <el-dropdown-item :command="-1" class="dropdown-header">
                  请选择简历
                </el-dropdown-item>
                <div class="dropdown-divider"></div>
                <div class="dropdown-scrollable">
                  <el-dropdown-item
                      v-for="(item, index) in legoCreateList"
                      :key="index"
                      :command="index"
                      class="resume-item"
                  >
                    <div class="resume-item-date">{{ formatDate(new Date(item.createDate)) }}</div> |
                    <div class="resume-item-title">{{ item.title }}</div>
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
              <div v-else class="loading-dropdown">
                <el-icon class="loading-icon"><i class="el-icon-loading"></i></el-icon>
                加载中...
              </div>
            </template>
          </el-dropdown>
        </div>

        <div class="resume-preview-container" :class="{ 'has-resume': selecting !== -1 }">
          <transition name="resume-fade">
            <resume-preview v-if="selecting !== -1 && !loadingPreview" :show-line="false" class="resume-preview"></resume-preview>
            <div v-else-if="loadingPreview" class="empty-state loading">
              <el-icon class="empty-icon spinning">
                <DocumentAdd />
              </el-icon>
              <h3 class="empty-title">简历加载中</h3>
              <p class="empty-desc">请稍等片刻...</p>
            </div>
            <div v-else class="empty-state">
              <el-icon class="empty-icon">
                <DocumentAdd />
              </el-icon>
              <h3 class="empty-title">暂无选中的简历</h3>
              <p class="empty-desc">请从上方下拉菜单中选择一份简历来查看详情和优化建议</p>
            </div>
          </transition>
        </div>
      </div>

      <!-- Right column: Job details -->
      <div class="job-details-section">
        <div class="job-search-container">
          <div class="input-group">
            <label class="input-label">
              <el-icon><OfficeBuilding /></el-icon>
              意向公司
            </label>
            <el-autocomplete
                v-model="company"
                :fetch-suggestions="(queryString: string, cb: any) => cb(company_history)"
                clearable
                class="custom-input"
                placeholder="请输入意向公司名称"
                :popper-class="'company-suggestions'"
            >
              <template #suffix>
                <el-icon class="input-icon"><Edit /></el-icon>
              </template>
            </el-autocomplete>
          </div>

          <div class="input-group">
            <label class="input-label">
              <el-icon><Briefcase /></el-icon>
              意向岗位
            </label>
            <el-autocomplete
                v-model="post"
                :fetch-suggestions="(queryString: string, cb: any) => cb(post_history)"
                clearable
                class="custom-input"
                placeholder="请输入意向岗位名称"
                :popper-class="'post-suggestions'"
            >
              <template #suffix>
                <el-icon class="input-icon"><Edit /></el-icon>
              </template>
            </el-autocomplete>
          </div>

          <el-button
              class="search-button"
              type="primary"
              @click="search"
              :loading="searching"
              :disabled="!company || !post"
          >
            <el-icon><Search /></el-icon>
            检索岗位要求
          </el-button>
        </div>

        <div class="requirements-container">
          <label class="input-label requirements-label">
            <el-icon><DocumentAdd /></el-icon>
            岗位要求/加分项
          </label>
          <el-input
              type="textarea"
              v-model="post_requirement"
              resize="none"
              class="requirements-textarea"
              placeholder="您可手动输入岗位要求，也可点击「检索岗位要求」以自动填充..."
              :rows="10"
          >
          </el-input>
        </div>
      </div>
    </div>

    <!-- Footer with action buttons -->
    <div class="page-footer">
      <div class="footer-content">
        <div class="footer-info">
          <div class="info-item">
            <span class="info-label">已选简历:</span>
            <span class="info-value">{{ selecting !== -1 ? (legoCreateList[selecting]?.title || '未选择') : '未选择' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">意向公司:</span>
            <span class="info-value">{{ company || '未填写' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">意向岗位:</span>
            <span class="info-value">{{ post || '未填写' }}</span>
          </div>
        </div>

        <el-button
            type="primary"
            class="next-button"
            @click="finish"
            :disabled="searching || selecting === -1 || !company || !post || !post_requirement"
        >
          下一步
          <el-icon class="next-icon"><ArrowRight /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');

.interview-setting-container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 80px);
  max-height: 100vh;
  padding: 0 20px;
  font-family: 'Noto Sans SC', sans-serif;
  opacity: 0;
  transform: translateY(10px);
  transition: opacity 0.5s ease, transform 0.5s ease;

  &.fade-in {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  padding: 20px 0;
  text-align: center;

  .page-title {
    font-size: 28px;
    font-weight: 700;
    color: #2c3e50;
    margin: 0 0 15px;

    .highlight {
      color: #409eff;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -2px;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(90deg, #409eff, #53a8ff);
        border-radius: 2px;
      }
    }
  }

  .progress-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 400px;
    margin: 0 auto;

    .progress-bar {
      width: 100%;
      height: 8px;
      background-color: #ebeef5;
      border-radius: 4px;
      overflow: hidden;
      margin-bottom: 5px;

      .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #409eff, #53a8ff);
        border-radius: 4px;
        transition: width 0.5s ease;
      }
    }

    .progress-text {
      font-size: 12px;
      color: #909399;
      align-self: flex-end;
    }
  }
}

.content-container {
  display: flex;
  flex: 1;
  gap: 20px;
  max-height: calc(100vh - 200px);

  .resume-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .section-header {
      padding: 15px;
      border-bottom: 1px solid #ebeef5;
    }

    .resume-selector {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: 10px 15px;
      border-radius: 6px;
      background-color: #f5f7fa;
      transition: all 0.3s ease;

      &:hover {
        background-color: #ecf5ff;
      }

      &.has-selection {
        background-color: #ecf5ff;
        border: 1px solid #d9ecff;
      }

      .selector-icon {
        font-size: 18px;
        color: #409eff;
        margin-right: 10px;
      }

      .selector-text {
        flex: 1;
        font-size: 15px;
        font-weight: 500;
        color: #606266;
      }

      .dropdown-arrow {
        font-size: 14px;
        color: #909399;
        transform: rotate(90deg);
      }
    }

    .resume-preview-container {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      position: relative;
      background-color: #f5f7fa;
      transition: all 0.3s ease;

      &.has-resume {
        background-color: #ffffff;
      }

      .resume-preview {
        height: 100%;
        overflow-y: auto;
        overflow-x: hidden;
        padding: 15px;
      }
    }
  }

  .job-details-section {
    width: 40%;
    display: flex;
    flex-direction: column;
    gap: 20px;

    .job-search-container {
      display: flex;
      flex-direction: column;
      gap: 15px;
      background: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      padding: 20px;

      .input-group {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .search-button {
        align-self: flex-end;
        margin-top: 5px;
        display: flex;
        align-items: center;
        gap: 5px;
        font-weight: 500;
        height: 40px;

        .el-icon {
          font-size: 16px;
        }
      }
    }

    .requirements-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8px;
      background: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      padding: 20px;

      .requirements-textarea {
        flex: 1;
        font-family: 'Noto Sans SC', sans-serif;

        :deep(.el-textarea__inner) {
          height: 100%;
          font-family: 'Noto Sans SC', sans-serif;
          line-height: 1.6;
          padding: 12px;
          border-color: #dcdfe6;

          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
      }
    }
  }
}

.page-footer {
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;

  .footer-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .footer-info {
      display: flex;
      gap: 20px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 5px;

        .info-label {
          font-size: 14px;
          color: #909399;
        }

        .info-value {
          font-size: 14px;
          font-weight: 500;
          color: #606266;
          max-width: 150px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .next-button {
      display: flex;
      align-items: center;
      gap: 5px;
      font-weight: 500;
      padding: 12px 25px;

      .next-icon {
        font-size: 16px;
      }
    }
  }
}

.input-label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;

  .el-icon {
    font-size: 16px;
    color: #409eff;
  }

  &.requirements-label {
    margin-bottom: 5px;
  }
}

.custom-input {
  width: 100%;

  :deep(.el-input__inner) {
    height: 40px;
    border-radius: 6px;
    border-color: #dcdfe6;

    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
  }

  :deep(.el-input__suffix) {
    .input-icon {
      color: #c0c4cc;
      font-size: 16px;
      cursor: pointer;

      &:hover {
        color: #909399;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 2rem;
  text-align: center;

  &.loading {
    .empty-icon {
      color: #409eff;
    }
  }

  .empty-icon {
    font-size: 64px;
    color: #c0c4cc;
    margin-bottom: 1.5rem;

    &.spinning {
      animation: spin 2s infinite linear;
    }
  }

  .empty-title {
    font-size: 20px;
    color: #303133;
    margin-bottom: 1rem;
    font-weight: 500;
  }

  .empty-desc {
    font-size: 14px;
    color: #909399;
    max-width: 80%;
    line-height: 1.6;
  }
}

.custom-dropdown {
  min-width: 250px;
  max-width: 350px;

  :deep(.el-dropdown-menu__item) {
    padding: 8px 16px;
    line-height: 1.5;

    &.dropdown-header {
      font-weight: 600;
      color: #606266;
      font-size: 14px;
    }
  }

  .dropdown-divider {
    height: 1px;
    background-color: #ebeef5;
    margin: 5px 0;
  }

  .dropdown-scrollable {
    max-height: 250px;
    overflow-y: auto;

    .resume-item {
      display: flex;
      flex-direction: column;
      gap: 3px;

      .resume-item-date {
        font-size: 12px;
        color: #909399;
      }

      .resume-item-title {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
      }

      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

.loading-dropdown {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;

  .loading-icon {
    margin-right: 8px;
    font-size: 16px;
  }
}

// Transitions
.resume-fade-enter-active,
.resume-fade-leave-active {
  transition: opacity 0.3s ease;
}

.resume-fade-enter-from,
.resume-fade-leave-to {
  opacity: 0;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// Responsive adjustments
@media (max-width: 1200px) {
  .content-container {
    flex-direction: column;

    .resume-section,
    .job-details-section {
      width: 100%;
    }

    .resume-section {
      max-height: 400px;
    }

    .job-details-section {
      .requirements-container {
        .requirements-textarea {
          :deep(.el-textarea__inner) {
            height: 200px;
          }
        }
      }
    }
  }

  .page-footer {
    .footer-content {
      flex-direction: column;
      gap: 15px;

      .footer-info {
        width: 100%;
        justify-content: space-between;
      }

      .next-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}

@media (max-width: 768px) {
  .page-header {
    .page-title {
      font-size: 24px;
    }
  }

  .footer-info {
    flex-direction: column;
    gap: 10px;

    .info-item {
      .info-value {
        max-width: 200px;
      }
    }
  }
}
</style>